import {compose, lifecycle, withHandlers, withState} from "recompose"
import {DEV, env} from "../../../../shared/project-config"
import {message} from "antd"
import {get, postParam} from "server"
import timer from "libs/timer"
import React from "react"
import {defaultRouter} from "project-config"

const devData = env === DEV ? {
  phoneNo: '15928436227'
} : {}


const formCompose = compose(
  withState('_initData', '_setInitData', () => {
    const dynamicPhoneNo = localStorage.getItem('dynamicPhoneNo')
    if (dynamicPhoneNo) {
      return Object.assign(devData, {phoneNo: dynamicPhoneNo, remember: true})
    }
    return devData
  }),
  //密码登录接口信息
  withState('_serverMessage', '_setServerMessage', null),
  withState('_smsCodeLoading', '_setSmsCodeLoading', false),
  withState('_smsCodeRemainTime', '_setSmsCodeRemainTime', 0),
  withHandlers({
    onSubmit: ({_setSubmitting, _setServerMessage, history}) => {
      return (form) => {
        _setSubmitting(true)
        const submit = (values) => {
          const remember = values.remember
          postParam(`/auth/loginBySms`, values, true)
            .then(() => {
              if (remember) {
                localStorage.setItem('dynamicPhoneNo', values.phoneNo)
              } else {
                localStorage.removeItem('dynamicPhoneNo')
              }

              const redirect = localStorage.getItem('redirect_url')
              if (redirect) {
                localStorage.removeItem('redirect_url')
                window.location = redirect
                return
              }
              history.push(defaultRouter)
            })
            .catch(e => {
              _setServerMessage(e.message)
            })
            .finally(() => {
              _setSubmitting(false)
            })
        }
        form.validateFields()
          .then(submit)
          .catch(() => {
            _setSubmitting(false)
          })
      }
    },
    sendSmsVerifyCode: ({_setSmsCodeLoading, _setSmsCodeRemainTime}) => {
      return (form) => {
        _setSmsCodeLoading(true)
        const send = (values) => {
          _setSmsCodeRemainTime(-1)
          get('/sms/dynamic', {phoneNo: values.phoneNo}, (data) => {
            message.info("短信发送过快，请稍候尝试")
            const n = (/(\d)+/g.exec(data.message)[0]).trim()
            timer(_setSmsCodeRemainTime, n)
          })
            .then((data) => {
              if (data) {
                message.success("验证码发送成功，有效期5分钟，请注意接收！")
                _setSmsCodeRemainTime(59)
                timer(_setSmsCodeRemainTime)
              }
            })
            .finally(() => _setSmsCodeLoading(false))
        }
        form.validateFields(['phoneNo'])
          .then(send)
          .catch(() => _setSmsCodeLoading(false))
      }
    }
  }),
  withHandlers({
    onInputChange: ({setAvatar}) => {
      return (event) => {
        const localAvatar = localStorage.getItem(`${event.target.value}_avatar`)
        if (localAvatar && localAvatar !== 'null') {
          setAvatar(localAvatar)
        }
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {setAvatar} = this.props
      const passwordAccount = localStorage.getItem('dynamicPhoneNo')
      const localAvatar = localStorage.getItem(`${passwordAccount}_avatar`)
      if (localAvatar && localAvatar !== 'null') {
        setAvatar(localAvatar)
      }
    }
  })
)

export default formCompose